package org.k.vmmock.filter;

import org.k.vmmock.util.Conf;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by hengxianwang on 16-10-29.
 */
public class ForwardFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        if (forward(request, response)) {
            return;
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }

    protected boolean forward(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        InputStream in = new FileInputStream(new File(Conf.getBasePath(true) + Conf.get("routers_file")));;
        Properties properties = new Properties();
        try {
            properties.load(in);
            String contextPath = req.getContextPath();
            String requestURI = req.getRequestURI().substring(contextPath.length());
            String target = properties.getProperty(requestURI);
            if (target != null) {
                System.out.println("url:" + contextPath + ", forward to " + target);
                req.getRequestDispatcher(target).forward(req, resp);
                return true;
            }
        }finally {
            if(in != null) in.close();
        }
        return false;
    }

}
